import { useEffect } from "react";
import { Space, message, Form, Select } from "antd";
import { Button } from "@douyinfe/semi-ui";
import { useModel } from "umi";
import { useReactive } from "ahooks";

import useUpdateApplication from "../../hooks/application/organization/useUpdateApplication";
import { useOrganizationDatabase } from "../../hooks/databases";

const UpdateDatabaseVersion = ({ application, index, database, appData, updateDatabases, reloadData }) => {
    const [form] = Form.useForm();
    const { onCloseGlobalModal } = useModel("global.modal");
    const { updateApplication } = useUpdateApplication();
    const { loadDatabaseVersionsByDatabaseName, versions, versionLoading } = useOrganizationDatabase();

    const state = useReactive({
        submitLoading: false,
        databaseName: "",
        selectedDatabase: null,
    });

    useEffect(() => {
        if (database.databaseName) {
            loadDatabaseVersionsByDatabaseName(database.databaseName);
        }
    }, [database.databaseName]);

    const onFinish = (values) => {
        appData[index].versionNo = values.versionNo;
        updateApplication(application.appUuid, { appData }, (res) => {
            if (res) {
                message.success("成功更新应用信息");
                updateDatabases(appData);
                reloadData && reloadData();
                onCloseGlobalModal();
            }
        });
    };

    return (
        <Form form={form} onFinish={onFinish} layout="horizontal" labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} style={{ padding: 20 }}>
            <Form.Item label="数据库模型说明">{database.title}</Form.Item>

            <Form.Item label="数据库模型名称">{database.databaseName}</Form.Item>

            <Form.Item label="数据库模型版本" name="versionNo" rules={[{ required: true, message: "请选择数据库模型版本" }]}>
                <Select allowClear loading={versionLoading}>
                    {versions.map((item, index) => (
                        <Select.Option key={index} value={item.versionNo}>
                            {item.versionNo}
                        </Select.Option>
                    ))}
                </Select>
            </Form.Item>

            <div style={{ textAlign: "center" }}>
                <Space>
                    <Button loading={state.submitLoading} type="primary" htmlType="submit">
                        更新
                    </Button>
                    <Button loading={state.submitLoading} htmlType="button" onClick={() => form.resetFields()}>
                        重置
                    </Button>
                </Space>
            </div>
        </Form>
    );
};

export default UpdateDatabaseVersion;
